from typing import Dict, List

import pandas as pd

from Processor.SignalProcessor import SignalProcessor
from model.FaultDetectionConfig import FaultDetectionConfig


class RMSAnalyzer:
    """RMS分析器"""

    def __init__(self, config: FaultDetectionConfig):
        self.config = config
        self.processor = SignalProcessor()

    def extract_multi_cycle_rms(self, df: pd.DataFrame, t_center: pd.Timestamp,
                                pre_cycles: int = 2, post_cycles: int = 5) -> Dict:
        """
        提取故障点前后多个周期的RMS值

        Args:
            df: 数据DataFrame
            t_center: 故障中心时间
            pre_cycles: 前置周期数
            post_cycles: 后置周期数

        Returns:
            RMS结果字典
        """
        result = {}
        cols = [col for col in df.columns if col != 'Freq']

        if not cols:
            raise ValueError("DataFrame中没有可用于计算RMS的有效列")

        # 处理前置周期
        for i in range(pre_cycles, 0, -1):
            cycle_data = self.processor.extract_cycle_data(df, t_center, -i, self.config)
            result[f'前第{i}周波'] = self._compute_cycle_rms(cycle_data, cols)

        # 处理后置周期
        for i in range(1, post_cycles + 1):
            cycle_data = self.processor.extract_cycle_data(df, t_center, i, self.config)
            result[f'后第{i}周波'] = self._compute_cycle_rms(cycle_data, cols)

        return result

    def _compute_cycle_rms(self, segment: pd.DataFrame, cols: List[str]) -> Dict:
        """计算单个周期的RMS值"""
        res = {}
        for col in cols:
            if col not in segment.columns:
                continue

            sig = segment[col].values
            res[col] = self.processor.compute_rms_standard(sig)
        return res